package com.wm.blog_common.context;

import com.wm.blog_common.constatnt.ContextConstant;
import com.wm.blog_common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 *@ClassName BaseContextHandler
 *@Description 管理后台登录上上下文
 *@Author 半卷流年
 *@Date 2020/9/25 16:18
 */
@Slf4j
public class AdminBaseContextHandler {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void setUserNameAndUserId(String userName,Long id){
        log.info("设置值的线程:{}", Thread.currentThread().getName());
        set(ContextConstant.ADMIN_USER_NAME,userName);
        set(ContextConstant.ADMIN_ID,id);
    }


    public static String getAdminUserName(){
       return get(ContextConstant.ADMIN_USER_NAME);
    }

    public static Long getAdminUserId(){
        String adminId = get(ContextConstant.ADMIN_ID);
        return StringUtils.isNotEmpty(adminId) ? Long.parseLong(adminId) : 0L;
    }

    private static void set(String key,Object value){
        Map<String, Object> map = threadLocal.get();
        if(CollectionUtils.isEmpty(map)){
            map = new HashMap<>();
           threadLocal.set(map);
        }
        map.put(key,value);
    }

    public static String get(String key){
        log.info("获取值的线程:{}", Thread.currentThread().getName());
        Map<String, Object> map = threadLocal.get();
        if(Objects.isNull(map)){
            map = Collections.emptyMap();
        }
        return returnObjectToString(map.getOrDefault(key,null));
    }


    public static void remove(){
        threadLocal.remove();
    }


    private static String returnObjectToString(Object value) {
        return value == null ? null : value.toString();
    }

    private static Long returnObjectToLong(Object value) {
        return value == null ? null : Long.parseLong(value.toString());
    }

}
